const express = require('express')
const mongoose = require('mongoose')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const UserModel = require('./models/user')
const server = express()

server.use(express.json())
server.use(express.urlencoded({ extended: true }))

const uri = 'mongodb://127.0.0.1:27017/migu'
mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('数据库连接成功')
}).catch((ere) => {
  console.log('数据库连接失败',ere)
})

server.use((req, res, next)=> {
  // 设置是否运行客户端设置 withCredentials
    // 即在不同域名下发出的请求也可以携带 cookie
    res.header("Access-Control-Allow-Credentials",true)
    // 第二个参数表示允许跨域的域名，* 代表所有域名
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS') // 允许的 http 请求的方法
    // 允许前台获得的除 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 这几张基本响应头之外的响应头
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
    if (req.method == 'OPTIONS') {
        res.sendStatus(200)
    } else {
        next()
    }
})

// 登录
server.post('/api/login', async (req, res) => {

  const username = req.body.username
  const password = req.body.password
  let isok = false
  const user = await UserModel.findOne({ username })
  if (user) {
    isok = await bcryptjs.compare(password,user.password)
  }
  if (isok) {
    const token = jwt.sign({ username: username,userId: user._id },'MYgod')
    res.send({
      code: 0,
      msg: '登录成功',
      data: {
        userInfo: {
          username: user.username,
          userId: user._id
        },
        token: token
      }
    })
  } else {
    res.send({
      code: -1,
      msg: '用户名或密码错误'
    })
  }
})

//注册
server.post('/api/registry', async (req,res) => {
  const username = req.body.username
  const password = req.body.password
  const user = new UserModel({
    username: username,
    password: await bcryptjs.hash(password, 11)
  })
  await user.save()
  res.send({
    code: 0,
    msg: '注册成功'
  })
})
server.listen(3000)
